package com.zhl.study.controller;

import com.zhl.study.base.ResponseFactory;
import com.zhl.study.base.Result;
import com.zhl.study.service.IEmailService;
import com.zhl.study.vo.EmailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@Slf4j
@RestController
@RequestMapping("api/")
@Api(value = "邮件", tags = "邮件")
public class EmailController {

    @Autowired
    IEmailService iEmailService;
    @Autowired
    private TemplateEngine templateEngine;

    @PostMapping("/sendSimpleEmail")
    @ApiOperation(httpMethod = "POST", value = "发简单文本邮件")
    public Result sendSimpleEmail(@RequestBody EmailVO vo) {
        iEmailService.sendSimpleEmail(vo.getTo(), vo.getSubject(), vo.getText());
        return ResponseFactory.ok();
    }

    @PostMapping("/sendComplexEmail")
    @ApiOperation(httpMethod = "POST", value = "发送复杂邮件")
    public Result sendComplexEmail(@RequestBody EmailVO vo) {
        iEmailService.sendComplexEmail(vo.getTo(), vo.getSubject(), vo.getText(), vo.getFilePath(), vo.getRscId(), vo.getRscPath());
        return ResponseFactory.ok();
    }

    @PostMapping("/sendTemplateEmail")
    @ApiOperation(httpMethod = "POST", value = "发模板邮件")
    public Result sendTemplateEmail(@RequestBody EmailVO vo) {
        Context context = new Context();
        context.setVariable("username", vo.getUsername());
        context.setVariable("code", vo.getCode());
        // 使用TemplateEngine设置要处理的模板页面
        String emailContent = templateEngine.process("emailTemplate_vercode", context);
        iEmailService.sendTemplateEmail(vo.getTo(), vo.getSubject(), emailContent);
        return ResponseFactory.ok();
    }
}
